import Taro from '@tarojs/taro'
import { useSnapshot } from 'valtio'

import * as A from '@/apis/user'
import { useAMap } from './useAMap'
import derivedState, { userState } from '@/stores/user'

export function useUserStore() {
  const { getLocation } = useAMap()
  const { geo, openid, userInfo } = useSnapshot(userState)
  const { city, province, balance, isAuthed } = useSnapshot(derivedState)

  const login = async () => {
    if (openid) return

    const res = await Taro.login()

    if (res.code) {
      const info = await A.wxlogin(res.code)

      userState.openid = info.openid
      userState.userInfo = info
    }
  }

  const getGeo = async () => {
    const res = await getLocation()

    userState.geo = res
  }

  const getUserInfo = async () => {
    if (!openid) return

    const res = await A.getUserInfo(openid)

    console.log('[get user info]', res)

    userState.userInfo = {
      ...userState.userInfo,
      ...res,
    }

    return res
  }

  return {
    geo,
    openid,
    balance,
    userInfo,
    city,
    province,
    isAuthed,
    login,
    getGeo,
    getUserInfo,
  }
}
